const crypto = require('crypto');

/**
 * 加密工具类
 */
class CryptorUtils {

  // 公开这个key，因为数据并不是很重要，防君子不防小人
  static defaultKey = '98af65aeg4col6de';

  static defaultIV = '1098574621234098';

  /**
   * 加密
   * @param data
   */
  static encrypt = (data) => {
    if(data) {
      const cipher = crypto.createCipheriv('aes-128-cbc', CryptorUtils.defaultKey, CryptorUtils.defaultIV);
      let crypted = cipher.update(typeof data === 'string' ? data : JSON.stringify(data), 'utf8', 'binary');
      crypted += cipher.final('binary');
      crypted = new Buffer(crypted, 'binary').toString('base64');
      return crypted;
    }
    return data;
  }

  /**
   * 解密
   * @param cipher
   */
  static decrypt = (cipher) => {
    try {
      cipher = new Buffer(cipher, 'base64').toString('binary');
      const decipher = crypto.createDecipheriv('aes-128-cbc', CryptorUtils.defaultKey, CryptorUtils.defaultIV);
      let decoded = decipher.update(cipher, 'binary', 'utf8');
      decoded += decipher.final('utf8');
      return JSON.parse(decoded);
    } catch (e) {
      return cipher;
    }
  }
}

export default CryptorUtils;
